package com.school.common.interceptor;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.school.common.constant.Constant;

/**
 * @author gaobiao
 * 
 */
public class AuthorizationInterceptor extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5169476540459753351L;
	private static Logger logger = Logger.getLogger(AuthorizationInterceptor.class);
	public static String[] whiteList = { "loginDo", "login", "logout", "logError" };

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com
	 * .opensymphony.xwork2.ActionInvocation)
	 */
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext ctx = invocation.getInvocationContext();
		for (String action : whiteList) {
			if (ctx.getName().equals(action)) {
				return invocation.invoke();
			}
		}
		ActionSupport actionSupport = (ActionSupport) invocation.getAction();
		HttpSession session = ServletActionContext.getRequest().getSession(false);
		if (session==null) {
			actionSupport.addActionError("登陆超时，请重新登陆");
			return "unlogin";
		}
		// 如果没有用户的session信息则无法通过拦截器
		if (session.getAttribute(Constant.SESSION_KEY_ADMIN) == null) {
			actionSupport.addActionError("请先登录系统");
			return "unlogin";
		}
		return invocation.invoke();
	}

}
